<template>
  <div class="shenlun-container">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="大类别">
          <el-select v-model="searchForm.category" placeholder="请选择大类别" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小类别">
          <el-select v-model="searchForm.subCategory" placeholder="请选择小类别" clearable>
            <el-option
              v-for="item in subCategoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchShenLunItems">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="content-card">
      <template #header>
        <div class="card-header">
          <span>申论题目管理</span>
          <div>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">批量删除</el-button>
            <el-button type="primary" @click="showAddDialog">添加申论题目</el-button>
          </div>
        </div>
      </template>

      <el-table :data="shenlunItems" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="category" label="大类别" width="120" />
        <el-table-column prop="subCategory" label="小类别" width="120" />
        <el-table-column prop="material" label="给定资料" show-overflow-tooltip>
          <template #default="scope">
            <div v-html="truncateText(scope.row.material, 50)"></div>
          </template>
        </el-table-column>
        <el-table-column prop="question" label="提问" show-overflow-tooltip>
          <template #default="scope">
            <div v-html="truncateText(scope.row.question, 50)"></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteShenLunItemHandler(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
    >
      <el-form :model="currentItem" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="大类别" prop="category">
          <el-select v-model="currentItem.category" placeholder="请选择大类别" @change="handleCategoryChange">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小类别" prop="subCategory">
          <el-select v-model="currentItem.subCategory" placeholder="请选择小类别">
            <el-option
              v-for="item in filteredSubCategoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="给定资料" prop="material">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="materialEditorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden;"
              v-model="currentItem.material"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleMaterialCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="提问" prop="question">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="questionEditorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 200px; overflow-y: hidden;"
              v-model="currentItem.question"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleQuestionCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="参考答案" prop="answer">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="answerEditorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden;"
              v-model="currentItem.answer"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleAnswerCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveShenLunItem">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllShenLunItems,
  addShenLunItem,
  updateShenLunItem,
  deleteShenLunItem,
  searchShenLunItems as apiSearchShenLunItems,
  deleteShenLunItems
} from '@/api/shenlun'
import type { ShenLunItem } from '@/types/shenlun'

// 富文本编辑器相关导入
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { createEditorRef, getEditorConfig, getToolbarConfig, createEditorCallback } from '@/utils/editorUtils'

// 数据相关
const shenlunItems = ref<ShenLunItem[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedIds = ref<number[]>([])

// 富文本编辑器相关
const materialEditorRef = createEditorRef()
const questionEditorRef = createEditorRef()
const answerEditorRef = createEditorRef()
const mode = 'default'
const editorConfig = getEditorConfig('请输入内容...', '申论题目')
const toolbarConfig = getToolbarConfig()
const handleMaterialCreated = createEditorCallback(materialEditorRef)
const handleQuestionCreated = createEditorCallback(questionEditorRef)
const handleAnswerCreated = createEditorCallback(answerEditorRef)

// 搜索表单
const searchForm = reactive({
  category: '',
  subCategory: ''
})

// 当前编辑项
const currentItem = reactive<ShenLunItem>({
  id: undefined,
  category: '',
  subCategory: '',
  material: '',
  question: '',
  answer: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 表单验证规则
const rules = {
  category: [
    { required: true, message: '请选择大类别', trigger: 'change' }
  ],
  material: [
    { required: true, message: '请输入给定资料', trigger: 'blur' }
  ],
  question: [
    { required: true, message: '请输入提问内容', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref()

// 大类别选项
const categoryOptions = [
  { value: '概括归纳', label: '概括归纳' },
  { value: '综合分析', label: '综合分析' },
  { value: '解决问题', label: '解决问题' },
  { value: '公文写作', label: '公文写作' },
  { value: '文章写作', label: '文章写作' }
]

// 小类别选项
const subCategoryOptions = [
  // 概括归纳
  { value: '概括题', label: '概括题', parent: '概括归纳' },
  { value: '归纳题', label: '归纳题', parent: '概括归纳' },
  
  // 综合分析
  { value: '词句解释', label: '词句解释', parent: '综合分析' },
  { value: '观点分析', label: '观点分析', parent: '综合分析' },
  { value: '现象分析', label: '现象分析', parent: '综合分析' },
  { value: '要素分析', label: '要素分析', parent: '综合分析' },
  { value: '比较分析', label: '比较分析', parent: '综合分析' },
  
  // 解决问题
  { value: '单一对策', label: '单一对策', parent: '解决问题' },
  { value: '复合对策', label: '复合对策', parent: '解决问题' },
  { value: '变异对策', label: '变异对策', parent: '解决问题' },
  
  // 公文写作
  { value: '普适类', label: '普适类', parent: '公文写作' },
  { value: '提纲类', label: '提纲类', parent: '公文写作' },
  { value: '要点类', label: '要点类', parent: '公文写作' },
  
  // 文章写作
  { value: '解释类', label: '解释类', parent: '文章写作' },
  { value: '分析类', label: '分析类', parent: '文章写作' },
  { value: '对策类', label: '对策类', parent: '文章写作' }
]

// 根据大类别过滤小类别选项
const filteredSubCategoryOptions = computed(() => {
  if (!currentItem.category) {
    return []
  }
  return subCategoryOptions.filter(item => item.parent === currentItem.category)
})

// 截取文本显示
const truncateText = (text: string, length: number) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 处理大类别变化
const handleCategoryChange = () => {
  // 清空小类别选择
  currentItem.subCategory = ''
}

// 获取所有申论题目
const fetchShenLunItems = async () => {
  try {
    const res: any = await getAllShenLunItems()
    if (res.code === 200) {
      shenlunItems.value = res.data
      total.value = res.data.length
    } else {
      ElMessage.error(res.message || '获取申论题目失败')
    }
  } catch (error: any) {
    ElMessage.error('获取申论题目失败: ' + (error.message || error))
  }
}

// 搜索申论题目
const searchShenLunItems = async () => {
  try {
    const res: any = await apiSearchShenLunItems({
      category: searchForm.category,
      subCategory: searchForm.subCategory
    })
    if (res.code === 200) {
      shenlunItems.value = res.data
      total.value = res.data.length
    } else {
      ElMessage.error(res.message || '搜索申论题目失败')
    }
  } catch (error: any) {
    ElMessage.error('搜索申论题目失败: ' + (error.message || error))
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.category = ''
  searchForm.subCategory = ''
  fetchShenLunItems()
}

// 显示添加对话框
const showAddDialog = () => {
  // 重置表单
  Object.assign(currentItem, {
    id: undefined,
    category: '',
    subCategory: '',
    material: '',
    question: '',
    answer: ''
  })
  dialogTitle.value = '添加申论题目'
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (item: ShenLunItem) => {
  // 填充表单数据
  Object.assign(currentItem, item)
  dialogTitle.value = '编辑申论题目'
  dialogVisible.value = true
}

// 保存申论题目
const saveShenLunItem = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let res: any
        if (currentItem.id) {
          // 更新
          res = await updateShenLunItem(currentItem)
        } else {
          // 添加
          res = await addShenLunItem(currentItem)
        }
        
        if (res.code === 200) {
          ElMessage.success(res.message || (currentItem.id ? '更新成功' : '添加成功'))
          dialogVisible.value = false
          fetchShenLunItems()
        } else {
          ElMessage.error(res.message || (currentItem.id ? '更新失败' : '添加失败'))
        }
      } catch (error: any) {
        ElMessage.error((currentItem.id ? '更新失败' : '添加失败') + ': ' + (error.message || error))
      }
    }
  })
}

// 删除申论题目
const deleteShenLunItemHandler = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个申论题目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res: any = await deleteShenLunItem(id)
    if (res.code === 200) {
      ElMessage.success(res.message || '删除成功')
      fetchShenLunItems()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.message || error))
    }
  }
}


// 分页相关
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchShenLunItems()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchShenLunItems()
}

// 处理选择变化
const handleSelectionChange = (selection: ShenLunItem[]) => {
  selectedIds.value = selection.map(item => item.id as number)
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一个题目')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个题目吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res: any = await deleteShenLunItems(selectedIds.value)
    if (res.code === 200) {
      ElMessage.success(res.message || '批量删除成功')
      fetchShenLunItems()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + (error.message || error))
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchShenLunItems()
})
</script>

<style scoped>
.shenlun-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-card :deep(.el-form-item) {
  margin-right: 20px;
}

.search-card :deep(.el-select) {
  width: 200px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>